<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\web\ForbiddenHttpException;
use backend\models\SysItem;
use yii\data\Pagination;
use backend\models\Taozhuang;
use backend\models\TaozhuangPos;
use yii\db\ActiveRecord;
use yii\widgets\LinkPager;
use backend\models\GrpStyle;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use backend\models\GrpSpace;
use backend\models\GrpClass;
use backend\models\GrpColor;
use backend\models\SysItemStyle;
use backend\models\SysItemColor;
use backend\models\TaozhuangColor;
use backend\models\TaozhuangStyle;

class TzxController extends Controller
{
    public $layout='main_tzx';
//     public function beforeAction($action)
//     {
//         //如果未登录，则直接跳转
//         if(Yii::$app->user->isGuest){
//             return $this->redirect(['/site/login']);
//         }

//         if(\Yii::$app->user->can('tzx')){
//             return true;
//         }else{
//             throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
//         }
//     }

    public function actionIndex()
    {
        return $this->render('index');
    }
    
    public function actionTz()
    {
        return $this->render('tz',[
            'tzid'=>Yii::$app->request->get('tzid')
        ]);
    }
    //单品相关
    public function actionItemList()
    {
        $P=5;//5小页后翻页
        $page=Yii::$app->request->get('page',1);
        $pageSize=Yii::$app->request->get('pagesize');
        
        //获取处理class类别数据
        $cdt = GrpClass::find()->select('id')->where(['`id`%100000000'=>0])->asArray()->column();
        $row = GrpClass::find()->select(['id1'=>'class1.id','name1'=>'class1.`name`','id2'=>'class2.id','name2'=>'class2.`name`','id3'=>'class3.id','name3'=>'class3.`name`'])
                        ->from('grp_class class1')
                        ->join('LEFT JOIN','grp_class class2','class2.father  = `class1`.`id`')
                        ->join('LEFT JOIN','grp_class class3','class3.father  = `class2`.`id`')
                        ->where(['in','class1.id',$cdt])
                        ->asArray()
                        ->orderBy(['id1' => SORT_ASC, 'id2' => SORT_ASC, 'id3' =>  SORT_ASC])
                        ->all();
        $this::dealdata($row);
        $tclass = json_encode($this::dealdata($row));
        //获取处理style风格数据
        $father = GrpStyle::find()->select('father')->where(['>','father',0])->distinct()->asArray()->column();
        $tstyle = GrpStyle::find()->select(['id','name'])->where(['not',['in','id',$father]])->asArray()->all();
        $tstyle = json_encode($tstyle);
        //获取处理color色系数据
        $tcolor = GrpColor::find()->asArray()->all();
        $tcolor = json_encode($tcolor);
        
        if (Yii::$app->request->isAjax)
        {
            $totalCount=SysItem::find()->where(['app_return'=>1])->count();
            $pageHtml=null;
            $arr=[];$i=0;
            $pagination = new Pagination([
                'totalCount' => $totalCount,
                'page' => $page,
                'pageSize' => $pageSize,
            ]);
            $getClass = Yii::$app->request->get('class',null);
            $getlong = intval(Yii::$app->request->get('long',null));
            $getStyle = intval(Yii::$app->request->get('style',null));
            $getColor = intval(Yii::$app->request->get('color',null));
            $getPrice = intval(Yii::$app->request->get('price',null));
            if (!empty($getClass)){
                $sortName = GrpClass::findOne(['id'=>$getClass])['name'];
            }
            if (!empty($getStyle)){
                $styleName = GrpStyle::findOne(['id'=>$getStyle])['name'];
            }
            if (!empty($getColor)){
                $colorName = GrpColor::findOne(['id'=>$getColor])['name'];
            }
            if (!empty($getPrice)){
                switch ($getPrice)
                {
                    case 1:
                        $priceName = '0-2000';
                        break;
                    case 2:
                        $priceName = '2000-5000';
                        break;
                    case 3:
                        $priceName = '5000-10000';
                        break;
                    case 4:
                        $priceName = '10000-30000';
                        break;
                    case 5:
                        $priceName = '30000+';
                        break;
                    default:
                        echo "No number between 1 and 5";
                }
            }
            $query1 = SysItemStyle::find()->select('item_id')->where(['style_id'=>$getStyle])->asArray()->column();//风格
            $query2 = SysItemColor::find()->select('item_id')->where(['color_id'=>$getColor])->asArray()->column();//颜色
            switch ($getPrice)//价格
            {
                case 1:
                    $minPrice = 0;
                    $maxPrice = 2000;
                    break;
                case 2:
                    $minPrice = 2000;
                    $maxPrice = 5000;
                    break;
                case 3:
                    $minPrice = 5000;
                    $maxPrice = 10000;
                    break;
                case 4:
                    $minPrice = 10000;
                    $maxPrice = 30000;
                    break;
                case 5:
                    $minPrice = 30000;
                    $maxPrice = 9999999999;
                    break;
                default:
                    $minPrice = 0;
                    $maxPrice = 9999999999;
            }
            $models=SysItem::find()
                ->where(['app_return'=>1])
                ->orderBy('id DESC')
                ->offset($pagination->offset)
                ->limit($pagination->pageSize)
                ->with('defaultSmallImage')
                ->andFilterWhere(['between','class_id',$getClass,$getClass+$getlong])//类筛选
                ->andFilterWhere(['in','id',$query1])//风格
                ->andFilterWhere(['in','id',$query2])//颜色
                ->andFilterWhere(['between','price_base',$minPrice,$maxPrice])
                ->all();
            
            foreach ($models as $model)
            {
                $arr[$i++]=[
                    'id'=>$model->id,
                    'img'=>!empty($model->defaultSmallImage)?$model->defaultSmallImage->url:null,
                ];
            }
            
            if ($page>0&&($page+1)%$P==0){
                $_page=$page/$P;
                $_pageSize=$pageSize*$P;
                $pagination = new Pagination([
                    'totalCount' => $totalCount,
                    'page' => $_page,
                    'pageSize' => $_pageSize,
                ]);
                $pageHtml=LinkPager::widget(['pagination' => $pagination]);
            }
            echo json_encode([
                'itemList'=>$arr,
                'pageHtml'=>$pageHtml,
                'sortName'=>empty($sortName)?null:$sortName,
                'styleName'=>empty($styleName)?null:$styleName,
                'colorName'=>empty($colorName)?null:$colorName,
                'priceName'=>empty($priceName)?null:$priceName
                ],JSON_UNESCAPED_UNICODE);
        }
        else{
            $page=($page-1)*$P;
            return $this->render('item-list',[
                'page'=>$page,
                'pageSize'=>$pageSize,
                'res' => $tclass,
                'tstyle' => $tstyle,
                'tcolor' => $tcolor
            ]);
        }
    }
    protected function dealdata($row)
    {
        $i = 0;
        $j = 0;
        $m = 0;
        foreach ($row as $key => $val) {
            if ($key >0 && $val['id1'] == $row[$key-1]['id1']){//判断第一级是否相同
                if ($val['id2'] == $row[$key-1]['id2']) {
                    $m++;
                    $res[$i]['sub1'][$j]['sub2'][$m]['id3'] = $val['id3'];
                    $res[$i]['sub1'][$j]['sub2'][$m]['name3'] = $val['name3'];
                }else {
                    $j++;
                    $m = 0;
                    $res[$i]['sub1'][$j]['id2'] = $val['id2'];
                    $res[$i]['sub1'][$j]['name2'] = $val['name2'];
        
                    $res[$i]['sub1'][$j]['sub2'][$m]['id3'] = $val['id3'];
                    $res[$i]['sub1'][$j]['sub2'][$m]['name3'] = $val['name3'];
                }
            }else {
                if ($key >0){
                    $i++;
                }
                $j = 0;
                $m = 0;
                $res[$i]['id1'] = $val['id1'];
                $res[$i]['name1'] = $val['name1'];
        
                $res[$i]['sub1'][$j]['id2'] = $val['id2'];
                $res[$i]['sub1'][$j]['name2'] = $val['name2'];
        
                $res[$i]['sub1'][$j]['id2'] = $val['id2'];
                $res[$i]['sub1'][$j]['name2'] = $val['name2'];
        
                $res[$i]['sub1'][$j]['sub2'][$m]['id3'] = $val['id3'];
                $res[$i]['sub1'][$j]['sub2'][$m]['name3'] = $val['name3'];
            }
        };
        return $res;
    }
    //print_r($res);
    //        类别数据结构 $test = [
    //                  0=>[
    //                      'id1'=>'10000000',
    //                      'name1'=>'客厅',
    //                      'sub1'=>[
    //                               0=>['id2'=>'10100000',
    //                                   'name1'=>'沙发',
    //                                   'sub2'=>[
    //                                            0=>[
    //                                                'id3'=>'101010000',
    //                                                'name3'=>'单人沙发'
    //                                               ],
    //                                            1=>[
    //                                                'id3'=>'101020000',
    //                                                'name3'=>'双人沙发'
    //                                               ],
    //                                            2=>[
    //                                                'id3'=>'101030000',
    //                                                'name3'=>'三人沙发'
    //                                               ]
    //                                           ]
    //                                    ],
    //                                  1=>['id2'=>'10100000',
    //                                      'name1'=>'桌几',
    //                                      'sub2'=>[
    //                                          0=>[
    //                                              'id3'=>'102020000',
    //                                              'name3'=>'茶几'
    //                                          ],
    //                                          1=>[
    //                                              'id3'=>'102030000',
    //                                              'name3'=>'边桌'
    //                                          ],
    //                                          2=>[
    //                                              'id3'=>'101040000',
    //                                              'name3'=>'休闲桌'
    //                                          ]
    //                                      ]
    //                                  ]
    //                          ]
    //                       ],
    //                  1=>[],
    //                  2=>[]
    //                 ];
    
    public function actionGetItemInfo()
    {
        //if (Yii::$app->request->isAjax)
        $item_id=intval(Yii::$app->request->get('item_id'));
        $imgArr=explode(',', Yii::$app->request->get('img_type',''));
        $arr=SysItem::findOne(['id'=>$item_id]);
        echo json_encode($arr->getAllInfo($imgArr),JSON_UNESCAPED_UNICODE);
    }
    //套装相关
    public function actionTzList()
    {
        $P=5;//5小页后翻页
        $page=Yii::$app->request->get('page',1);
        $pageSize=Yii::$app->request->get('pagesize');
        
        //获取处理space空间数据
        $tspace = GrpSpace::find()->select(['id','name'])->where(['useing'=>1])->asArray()->all();
        $tspace = json_encode($tspace);
        //获取处理style风格数据
        $father = GrpStyle::find()->select('father')->where(['>','father',0])->distinct()->asArray()->column();
        $tstyle = GrpStyle::find()->select(['id','name'])->where(['not',['in','id',$father]])->asArray()->all();
        $tstyle = json_encode($tstyle);
        //获取处理color色系数据
        $tcolor = GrpColor::find()->asArray()->all();
        $tcolor = json_encode($tcolor);
        
        
        if (Yii::$app->request->isAjax)
        {
            $totalCount=Taozhuang::find()->where(['app_return'=>1])->count();
            $pageHtml=null;
            $arr=[];$i=0;
            $pagination = new Pagination([
                'totalCount' => $totalCount,
                'page' => $page,
                'pageSize' => $pageSize,
            ]);
            
            $getSpace = Yii::$app->request->get('space',null);
            $getStyle = intval(Yii::$app->request->get('style',null));
            $getColor = intval(Yii::$app->request->get('color',null));
            $getPrice = intval(Yii::$app->request->get('price',null));
            if (!empty($getSpace)){
                $spaceName = GrpClass::findOne(['id'=>$getSpace])['name'];
            }
            if (!empty($getStyle)){
                $styleName = GrpStyle::findOne(['id'=>$getStyle])['name'];
            }
            if (!empty($getColor)){
                $colorName = GrpColor::findOne(['id'=>$getColor])['name'];
            }
            if (!empty($getPrice)){
                switch ($getPrice)
                {
                    case 1:
                        $priceName = '0-2000';
                        break;
                    case 2:
                        $priceName = '2000-5000';
                        break;
                    case 3:
                        $priceName = '5000-10000';
                        break;
                    case 4:
                        $priceName = '10000-30000';
                        break;
                    case 5:
                        $priceName = '30000+';
                        break;
                    default:
                        echo "No number between 1 and 3";
                }
            }
            $query1 = TaozhuangStyle::find()->select('taozhuang_id')->where(['style_id'=>$getStyle])->asArray()->column();
            $query2 = TaozhuangColor::find()->select('taozhuang_id')->where(['color_id'=>$getColor])->asArray()->column();
            switch ($getPrice)
            {
                case 1:
                    $minPrice = 0;
                    $maxPrice = 2000;
                    break;
                case 2:
                    $minPrice = 2000;
                    $maxPrice = 5000;
                    break;
                case 3:
                    $minPrice = 5000;
                    $maxPrice = 10000;
                    break;
                case 4:
                    $minPrice = 10000;
                    $maxPrice = 30000;
                    break;
                case 5:
                    $minPrice = 30000;
                    $maxPrice = 9999999999;
                    break;
                default:
                    $minPrice = 0;
                    $maxPrice = 9999999999;
            }
            $models=Taozhuang::find()
                ->where(['app_return'=>1])
                ->orderBy('sid DESC')
                ->offset($pagination->offset)
                ->limit($pagination->pageSize)
                ->with('tzSmallImage')
                ->andFilterWhere(['space_id'=>$getSpace])
                ->andFilterWhere(['in','sid',$query1])
                ->andFilterWhere(['in','sid',$query2])
                ->andFilterWhere(['between','price_base',$minPrice,$maxPrice])
                ->all();
            foreach ($models as $model)
            {
                $arr[$i++]=[
                    'id'=>$model->sid,
                    'img'=>!empty($model->tzSmallImage)?$model->tzSmallImage->url:null,
                ];
            }
        
            if ($page>0&&($page+1)%$P==0){
                $_page=$page/$P;
                $_pageSize=$pageSize*$P;
                $pagination = new Pagination([
                    'totalCount' => $totalCount,
                    'page' => $_page,
                    'pageSize' => $_pageSize,
                ]);
                $pageHtml=LinkPager::widget(['pagination' => $pagination]);
            }
            echo json_encode([
                'itemList'=>$arr,
                'pageHtml'=>$pageHtml,
                'spaceName'=>empty($spaceName)?null:$spaceName,
                'styleName'=>empty($styleName)?null:$styleName,
                'colorName'=>empty($colorName)?null:$colorName,
                'priceName'=>empty($priceName)?null:$priceName
                ],JSON_UNESCAPED_UNICODE);
        }
        else{
            $page=($page-1)*$P;
            return $this->render('tz-list',[
                'page'=>$page,
                'pageSize'=>$pageSize,
                'tspace'=>$tspace,
                'tstyle'=>$tstyle,
                'tcolor'=>$tcolor
            ]);
        }
    }
    
    //套装获取默认图
    public function actionTzPosItem()
    {
        $tzid=Yii::$app->request->get('tzid',23);
        $res=TaozhuangPos::find()->where(['tzid'=>$tzid])->orderBy(['pos'=>'ASC','`order`'=>'ASC'])->with('sysItem','fitClass','defaultImg')->all();
        $arr=[];$i=0;$pos_class=[];
        foreach ($res as $item)
        {
            $pos=$item->pos;
            if (!isset($arr[$pos]))
            {
                $arr[$pos]=[
                    'info'=>[
                        'pos'=>$pos,
                        'current_index'=>0,
                        'pos_name'=>$item->show_name,
                        'class'=>$item->sysItem->class_id,
                        'class_order'=>$item->sysItem->class_name->t_order,
                        'father'=>$item->father,
                        'fit_class'=>!empty($item->fitClass)?$item->fitClass->grp_list:'',
                        'fit_space'=>!empty($item->fitSpace)?implode(',', $item->getFitSpace()):'',
                    ],
                    'items'=>[],
                ];
                $i=0;
            }
            $arr[$pos]['items'][$i]=[
                'pos_id'=>$item->id,
                'pos'=>$pos,
                'item_id'=>$item->item_id,
                'order'=>$item->order,
                'preview_img'=>$item->defaultImg->url,
                'main_img'=>$item->sysItem->defaultSmallImage->url,
                'width'=>$item->defaultImg->width,
                'height'=>$item->defaultImg->height,
                'x'=>$item->x,
                'y'=>$item->y,
                'anchor_x'=>$item->anchor_x,
                'anchor_y'=>$item->anchor_y,
                'zoom'=>$item->zoom,
                'mirror'=>$item->mirror,
                'rotate'=>$item->rotate,
                'current_fm_index'=>0,
                'fm_table'=>TaozhuangPos::getItemFbmt($item->id),
                'item_name'=>$item->sysItem->name,
                'item_price_base'=>$item->sysItem->price_base,
            ];
            $i++;
        }
        echo json_encode($arr,JSON_UNESCAPED_UNICODE);
    }
    //获取更多单品加入套装
    public function actionTzAddItem()
    {
        $page=Yii::$app->request->get('page',0)-1;
        $class=Yii::$app->request->get('class');
        $fit_class=Yii::$app->request->get('fit_class');
        $fit_space=Yii::$app->request->get('fit_space');
        $exclude=Yii::$app->request->get('exclude');
        $style=Yii::$app->request->get('style');
        $str1=$str2=$str3=$str4='';
        if (!strstr($fit_class, $class)){
            $fit_class==''?$fit_class=$class:$fit_class=$fit_class.','.$class;
        }
        if ($fit_class){
            $str1=" AND sys_item.class_id IN (".$fit_class.") ";
        }else{
            echo json_encode([]);
            return ;
        }
        if ($fit_space){
            $str2=" AND sys_item_space.space_id IN (".$fit_space.") ";
        }
        if ($exclude){
            $str3=" AND sys_item.id NOT IN (".$exclude.") ";
        }
        if($style){
            $str4=" AND sys_item_style.style_id=".$style." ";
        }
        $sql_count="SELECT sys_item_space.item_id, sys_item.`name`, sys_image.url
                	FROM sys_item_space,sys_image,base_sys_preview,sys_image img_preview,sys_item ".($str4!=''?"right join sys_item_style on sys_item.id=sys_item_style.item_id":'')."
                	WHERE sys_item.id=sys_item_space.item_id 
                    AND base_sys_preview.item_id=sys_item.id
                    AND base_sys_preview.img_tz_id=img_preview.id
                	AND sys_item.img_thumb_id=sys_image.id ".$str1.$str2.$str3.$str4." 
                	GROUP BY item_id";
        $pagination=new Pagination([
            'page'=>$page,
            'defaultPageSize'=>6,
            'totalCount' => ActiveRecord::findBySql($sql_count)->count(),
        ]);
        $sql="SELECT t.item_id,
            t.`name`,
            t.url AS main_img,
            fid,mid,
            base_sys_fabric.`name` AS fab_name,
            base_sys_material.`name` AS mat_name,
            img1.url AS fab_url,
            img2.url AS mat_url,
            img3.url AS fbmt_preview
            FROM 
            (
            	SELECT sys_item_space.item_id, sys_item.`name`, sys_image.url
            	FROM sys_item_space,sys_image,base_sys_preview,sys_image img_preview,sys_item ".($str4!=''?"right join sys_item_style on sys_item.id=sys_item_style.item_id":'')."
            	WHERE sys_item.id=sys_item_space.item_id 
                AND base_sys_preview.item_id=sys_item.id
                AND base_sys_preview.img_tz_id=img_preview.id
            	AND sys_item.img_thumb_id=sys_image.id ".$str1.$str2.$str3.$str4." 
            	GROUP BY item_id LIMIT ".$pagination->offset.",".$pagination->limit."
            ) t
            LEFT JOIN base_sys_preview ON base_sys_preview.item_id=t.item_id
            LEFT JOIN base_sys_fabric ON base_sys_fabric.id=base_sys_preview.fid
            LEFT JOIN base_sys_material ON base_sys_material.id=base_sys_preview.mid
            LEFT JOIN sys_image img1 ON img1.id=base_sys_fabric.img_small_id
            LEFT JOIN sys_image img2 ON img2.id=base_sys_material.img_small_id,
            sys_image img3 WHERE img3.id=base_sys_preview.img_tz_id";
//echo $sql;return ;
        $res=ActiveRecord::findBySql($sql)->asArray()->all();
        $arr=[];
        foreach ($res as $value)
        {
            if (!isset($arr[$value['item_id']])){
                $arr[$value['item_id']]=[];
            }
            $arr[$value['item_id']][count($arr[$value['item_id']])]=$value;
        }
        $pageHtml=LinkPager::widget([
            'pagination' => $pagination,
        ]);
        return json_encode([
            'items'=>$arr,
            'pageHtml'=>$pageHtml,
            'pos'=>Yii::$app->request->get('pos'),
        ],JSON_UNESCAPED_UNICODE);
    }
    //获取套装其他信息
    public function actionTzInfo()
    {
        $styleHtml=Html::dropDownList('style-list',null,ArrayHelper::map(GrpStyle::find()->asArray()->all(), 'id', 'name'),['class'=>'form-control','prompt'=>'风格选择']);
        $res=Taozhuang::findOne(['sid'=>Yii::$app->request->get('tzid')]);
        $arr=[
            'name'=>$res->name,
            'price'=>$res->price_base,
            'styleHtml'=>$styleHtml,
        ];
        echo json_encode($arr,JSON_UNESCAPED_UNICODE);
    }
}